package com.xtedu.examproject.controller;

import cn.hutool.json.JSONObject;
import com.google.gson.Gson;
import com.xtedu.examproject.entity.Role;
import com.xtedu.examproject.entity.Teacher;
import com.xtedu.examproject.service.RoleService;
import com.xtedu.examproject.service.TeacherService;
import com.xtedu.examproject.util.PageHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/teamanage/*")
public class TeacherServlet extends HttpServlet {
    private TeacherService teacherService;
    private RoleService roleService;
    private final static int pageSize = 5;

    public void init() {
        teacherService = new TeacherService();
        roleService = new RoleService();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        // 获取路径信息
        String pathInfo = req.getPathInfo();
        // 处理路径信息
        String path = (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("")) ? "/" : pathInfo;
        try {
            switch (path) {
                case "/addTeacher":
                    addTeacher(req, resp);
                    break;
                case "/deleteTeacher":
                    deleteTeacher(req, resp);
                    break;
                case "/searchTeacher":
                    queryTeacher(req, resp);
                    break;
                case "/updateTeacher":
                    updateTeacher(req, resp);
                    break;
                default:
                    showTeacherManage(req, resp);
                    break;
            }
        } catch (Exception e) {
            throw new ServletException("处理请求失败", e);
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        // 获取路径信息
        String pathInfo = req.getPathInfo();

        try {
            if (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("")) {
                showTeacherManage(req, resp);
            } else if (pathInfo.equals("/addTeacher")) {
                // 处理添加课程表单提交
                addTeacher(req, resp);
            } else if (pathInfo.equals("/deleteTeacher")) {
                deleteTeacher(req, resp);
            } else if (pathInfo.equals("/searchTeacher")) {
                queryTeacher(req, resp);
            } else if (pathInfo.equals("/updateTeacher")) {
                updateTeacher(req, resp);
            } else {
                showTeacherManage(req, resp);
            }
        } catch (Exception e) {
            throw new ServletException("处理请求失败", e);
        }
    }

    /**
     * 处理老师管理页面
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void showTeacherManage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            int pageIndex = req.getParameter("pageIndex") != null ? Integer.parseInt(req.getParameter("pageIndex")) : 1;
            PageHelper page = teacherService.findAllTeacherByPage(pageIndex, pageSize);

            // 获取所有角色信息
            List<Role> roles = roleService.findAll();

            // 构造完整的servlet名称，如果存在路径信息则将其与servlet路径拼接，否则直接使用servlet路径
            String servletName = req.getPathInfo() != null ? req.getServletPath() + req.getPathInfo() : req.getServletPath();
            page.setServletName(servletName);
            // 获取所有老师数据
            req.setAttribute("page", page);
            req.setAttribute("roles", roles);
        } catch (Exception e) {
            throw new ServletException("获取老师数据失败", e);
        }
        // 转发到老师管理页面
        req.getRequestDispatcher("/WEB-INF/views/teachermanage.jsp").forward(req, resp);
    }

    /**
     * 添加老师
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    public void addTeacher(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 读取请求体中的JSON数据
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            // 解析JSON数据
            Gson gson = new Gson();
            Teacher teacher = gson.fromJson(sb.toString(), Teacher.class);
            teacherService.insertTeacher(teacher);

            // 返回成功响应
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", true);
            responseJson.put("message", "老师信息添加成功");
            resp.getWriter().write(responseJson.toString());

        } catch (Exception e) {
            // 返回错误响应
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", false);
            responseJson.put("message", "添加老师信息失败: " + e.getMessage());
            resp.getWriter().write(responseJson.toString());
        }
    }

    /**
     * 删除老师
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    public void deleteTeacher(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            // 设置响应类型为JSON
            resp.setContentType("application/json;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");

            // 获取要删除的课程ID
            String teacherIdStr = req.getParameter("id");

            // 检查课程ID是否为空
            if (teacherIdStr != null && !teacherIdStr.isEmpty()) {
                try {
                    int teacherId = Integer.parseInt(teacherIdStr);

                    // 调用service层方法删除课程
                    boolean deleted = teacherService.deleteTeacherId(teacherId);

                    // 返回JSON响应
                    if (deleted) {
                        resp.getWriter().write("{\"success\":true,\"message\":\"课程删除成功\"}");
                    } else {
                        resp.getWriter().write("{\"success\":false,\"message\":\"课程删除失败，可能课程不存在\"}");
                    }
                } catch (NumberFormatException e) {
                    resp.getWriter().write("{\"success\":false,\"message\":\"课程ID格式错误\"}");
                }
            } else {
                resp.getWriter().write("{\"success\":false,\"message\":\"无效的课程ID\"}");
            }
        } catch (Exception e) {
            System.err.println("删除课程时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 查询老师
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    public void queryTeacher(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取要查询的类型
        String searchType = req.getParameter("searchType");
        //获取前端传递的参数
        String teacherSearchText = req.getParameter("teacherSearchText");
        int pageIndex = req.getParameter("pageIndex") != null ?
                Integer.parseInt(req.getParameter("pageIndex")) : 1;

        PageHelper page = null;

        if (teacherSearchText != null && !teacherSearchText.trim().isEmpty()) {
            teacherSearchText = teacherSearchText.trim();

            // 根据搜索类型调用不同的查询方法
            switch (searchType) {
                case "id":
                    int id = Integer.parseInt(teacherSearchText);
                    page = teacherService.findTeacherById(id, pageIndex, pageSize);
                    break;
                case "phone":
                    page = teacherService.findPagePhoneByTeacher(teacherSearchText, pageIndex, pageSize);
                    break;
                case "name":
                    page = teacherService.findTeacherByName(teacherSearchText, pageIndex, pageSize);
                    break;
                case "type":
                    page = teacherService.findTeacherByType(teacherSearchText, pageIndex, pageSize);
                    break;
            }
        } else {
            // 没有搜索条件，显示所有老师
            page = teacherService.findAllTeacherByPage(pageIndex, pageSize);
        }

        // 保存分页结果
        req.setAttribute("page", page);
        // 保存搜索参数用于页面显示和分页链接
        req.setAttribute("teacherSearchText", teacherSearchText);
        req.setAttribute("searchType", searchType);

        // 添加 servletName 设置
        String servletName = req.getServletPath() + "/searchTeacher";
        if (page != null) {
            page.setServletName(servletName);
        }

        req.getRequestDispatcher("/WEB-INF/views/teachermanage.jsp").forward(req, resp);
    }

    /**
     * 编辑老师信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     */
    public void updateTeacher(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            // 读取请求体中的JSON数据
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            // 解析JSON数据
            Gson gson = new Gson();
            Teacher teacher = gson.fromJson(sb.toString(), Teacher.class);

            // 检查必要字段是否为空
            if (teacher.getId() <= 0 ||
                    teacher.getName() == null || teacher.getName().trim().isEmpty() ||
                    teacher.getPhone() == null || teacher.getPhone().trim().isEmpty()) {

                // 返回错误响应
                JSONObject responseJson = new JSONObject();
                responseJson.put("success", false);
                responseJson.put("message", "所有字段不能为空");
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write(responseJson.toString());
                return;
            }

            // 调用service层更新方法
            boolean updated = teacherService.updateTeacherById(teacher);

            // 返回响应
            JSONObject responseJson = new JSONObject();
            if (updated) {
                responseJson.put("success", true);
                responseJson.put("message", "老师信息更新成功");
            } else {
                responseJson.put("success", false);
                responseJson.put("message", "老师信息更新失败");
            }

            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(responseJson.toString());

        } catch (Exception e) {
            // 处理其他异常
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", false);
            responseJson.put("message", "更新老师信息失败: " + e.getMessage());
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(responseJson.toString());
        }
    }


}
